<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 6.3.0">
<link rel="preconnect" href="https://fonts.googleapis.com" crossorigin>
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,300italic,400,400italic,700,700italic%7CZCOOL+QingKe+HuangYou:300,300italic,400,400italic,700,700italic%7CNoto+Sans+Simplified+Chinese:300,300italic,400,400italic,700,700italic%7CJetBrains+Mono:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">

<link rel="stylesheet" href="/lib/@fortawesome/fontawesome-free/css/all.min.css" integrity="sha256-HtsXJanqjKTc8vVQjO4YMhiqFoXkfBsjBWcX91T1jr8=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/animate.css/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="/lib/@fancyapps/ui/dist/fancybox/fancybox.css" integrity="sha256-RvRHGSuWAxZpXKV9lLDt2e+rZ+btzn48Wp4ueS3NZKs=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"wyatex.online","root":"/","images":"/images","scheme":"Pisces","darkmode":true,"version":"8.18.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":false,"height":500},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":true}}</script><script src="/js/config.js"></script>

    <meta name="description" content="在学习 TS 黑魔法（类型体操），建议先把前面的 TS 基础知识学好了，再来看进阶用法。 另外，即使已经进阶到高级选手了：不要滥用工具类型，对外暴露的 API，应该尽量多手动标注函数返回值类型。契约高于实现。">
<meta property="og:type" content="article">
<meta property="og:title" content="TypeScript黑魔法教学（1）：前置知识">
<meta property="og:url" content="https://wyatex.online/TypeScript/ts%E9%BB%91%E9%AD%94%E6%B3%95%E6%95%99%E5%AD%A6%EF%BC%881%EF%BC%89%EF%BC%9A%E5%89%8D%E7%BD%AE%E7%9F%A5%E8%AF%86/index.html">
<meta property="og:site_name" content="Wyatex&#96;s blog">
<meta property="og:description" content="在学习 TS 黑魔法（类型体操），建议先把前面的 TS 基础知识学好了，再来看进阶用法。 另外，即使已经进阶到高级选手了：不要滥用工具类型，对外暴露的 API，应该尽量多手动标注函数返回值类型。契约高于实现。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://wyatex.online/TypeScript/ts%E9%BB%91%E9%AD%94%E6%B3%95%E6%95%99%E5%AD%A6%EF%BC%881%EF%BC%89%EF%BC%9A%E5%89%8D%E7%BD%AE%E7%9F%A5%E8%AF%86/type-rel.png">
<meta property="og:image" content="https://wyatex.online/TypeScript/ts%E9%BB%91%E9%AD%94%E6%B3%95%E6%95%99%E5%AD%A6%EF%BC%881%EF%BC%89%EF%BC%9A%E5%89%8D%E7%BD%AE%E7%9F%A5%E8%AF%86/interface-type.png">
<meta property="article:published_time" content="2023-04-20T01:22:12.000Z">
<meta property="article:modified_time" content="2024-01-12T06:31:44.844Z">
<meta property="article:author" content="Wyatex">
<meta property="article:tag" content="前端">
<meta property="article:tag" content="学习笔记">
<meta property="article:tag" content="TypeScript">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://wyatex.online/TypeScript/ts%E9%BB%91%E9%AD%94%E6%B3%95%E6%95%99%E5%AD%A6%EF%BC%881%EF%BC%89%EF%BC%9A%E5%89%8D%E7%BD%AE%E7%9F%A5%E8%AF%86/type-rel.png">


<link rel="canonical" href="https://wyatex.online/TypeScript/ts%E9%BB%91%E9%AD%94%E6%B3%95%E6%95%99%E5%AD%A6%EF%BC%881%EF%BC%89%EF%BC%9A%E5%89%8D%E7%BD%AE%E7%9F%A5%E8%AF%86/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://wyatex.online/TypeScript/ts%E9%BB%91%E9%AD%94%E6%B3%95%E6%95%99%E5%AD%A6%EF%BC%881%EF%BC%89%EF%BC%9A%E5%89%8D%E7%BD%AE%E7%9F%A5%E8%AF%86/","path":"TypeScript/ts黑魔法教学（1）：前置知识/","title":"TypeScript黑魔法教学（1）：前置知识"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>TypeScript黑魔法教学（1）：前置知识 | Wyatex`s blog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">Wyatex`s blog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">97</span></a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">26</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">155</span></a></li><li class="menu-item menu-item-编程"><a href="/programming/" rel="section"><i class="fa fa-book fa-fw"></i>编程</a></li><li class="menu-item menu-item-蹲坑读物"><a href="/%E5%B9%B2%E8%B4%A7/%E5%BC%80%E5%8F%91%E4%BA%A4%E6%B5%81%E7%BE%A4%E5%88%86%E4%BA%AB%E8%AE%B0%E5%BD%95/" rel="section"><i class="fa fa-book fa-fw"></i>蹲坑读物</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9F%BA%E7%A1%80"><span class="nav-number">1.</span> <span class="nav-text">基础</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E7%B1%BB%E5%9E%8B%E5%85%B3%E7%B3%BB"><span class="nav-number">1.1.</span> <span class="nav-text">类型关系</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#never"><span class="nav-number">1.2.</span> <span class="nav-text">never</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%BA%94%E7%94%A8%E4%B8%80-%E8%81%94%E5%90%88%E7%B1%BB%E5%9E%8B%E4%B8%AD%E7%9A%84%E8%BF%87%E6%BB%A4"><span class="nav-number">1.2.1.</span> <span class="nav-text">应用一: 联合类型中的过滤</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%BA%94%E7%94%A8%E4%BA%8C%EF%BC%9A%E9%98%B2%E5%BE%A1%E6%80%A7%E7%BC%96%E7%A8%8B"><span class="nav-number">1.2.2.</span> <span class="nav-text">应用二：防御性编程</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#unknown"><span class="nav-number">1.3.</span> <span class="nav-text">unknown</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%81%94%E5%90%88%E7%B1%BB%E5%9E%8B"><span class="nav-number">1.4.</span> <span class="nav-text">联合类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%87%8D%E8%BD%BD%E7%AD%BE%E5%90%8D%E7%9A%84%E7%B1%BB%E5%9E%8B%E4%B8%8D%E4%BC%9A%E5%90%88%E5%B9%B6"><span class="nav-number">1.5.</span> <span class="nav-text">重载签名的类型不会合并</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%B3%9B%E5%9E%8B"><span class="nav-number">1.6.</span> <span class="nav-text">泛型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#extends-%E6%9D%A1%E4%BB%B6%E8%AF%AD%E5%8F%A5"><span class="nav-number">1.7.</span> <span class="nav-text">extends 条件语句</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%80%92%E5%BD%92"><span class="nav-number">1.8.</span> <span class="nav-text">递归</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%95%B0%E7%BB%84"><span class="nav-number">1.8.1.</span> <span class="nav-text">数组</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="nav-number">1.8.2.</span> <span class="nav-text">字符串</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%A5%BD%E7%94%A8%E7%9A%84%E5%B0%8F%E7%89%B9%E6%80%A7"><span class="nav-number">1.9.</span> <span class="nav-text">好用的小特性</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#name"><span class="nav-number">1.9.1.</span> <span class="nav-text">name</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Type-only-Field-Declarations"><span class="nav-number">1.9.2.</span> <span class="nav-text">Type-only Field Declarations</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%B1%BB%E5%9E%8B%E8%B0%93%E8%AF%8D-is"><span class="nav-number">1.9.3.</span> <span class="nav-text">类型谓词 is</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#interface-%E5%92%8C-type-%E5%85%B3%E9%94%AE%E5%AD%97"><span class="nav-number">2.</span> <span class="nav-text">interface 和 type 关键字</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%8D%E7%9B%B4%E8%A7%89%E7%9A%84%E4%B8%80%E4%BA%9B%E7%89%B9%E6%80%A7"><span class="nav-number">3.</span> <span class="nav-text">反直觉的一些特性</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%95%B0%E7%BB%84%E6%98%AF%E5%AF%B9%E8%B1%A1%E7%9A%84%E4%B8%80%E7%A7%8D"><span class="nav-number">3.1.</span> <span class="nav-text">数组是对象的一种</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#keyof-%E7%B4%A2%E5%BC%95%E6%98%AF%E5%85%AC%E6%9C%89%E5%B1%9E%E6%80%A7-key-%E7%9A%84%E8%81%94%E5%90%88"><span class="nav-number">3.2.</span> <span class="nav-text">keyof 索引是公有属性 key 的联合</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%9D%A1%E4%BB%B6%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%88%86%E5%B8%83%E5%BC%8F%E7%89%B9%E6%80%A7"><span class="nav-number">3.3.</span> <span class="nav-text">条件类型的分布式特性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AF%B9%E8%B1%A1%E5%AD%97%E9%9D%A2%E9%87%8F%E7%9A%84-excess-property-check"><span class="nav-number">3.4.</span> <span class="nav-text">对象字面量的 excess property check</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%A4%E6%96%ADnever"><span class="nav-number">3.5.</span> <span class="nav-text">判断never</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%88%AB%E7%9A%84%E4%B8%80%E4%BA%9B%E7%9F%A5%E8%AF%86%E7%82%B9"><span class="nav-number">4.</span> <span class="nav-text">别的一些知识点</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%85%A8%E5%B1%80%E6%A8%A1%E5%9D%97-vs-%E6%96%87%E4%BB%B6%E6%A8%A1%E5%9D%97"><span class="nav-number">4.1.</span> <span class="nav-text">全局模块 vs. 文件模块</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AD%97%E7%AC%A6%E4%B8%B2%E8%BD%AC%E6%95%B0%E5%AD%97"><span class="nav-number">4.2.</span> <span class="nav-text">字符串转数字</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%98%A0%E5%B0%84%E7%B1%BB%E5%9E%8B-key%E5%80%BC%E7%9A%84%E4%BA%A4%E9%9B%86%E4%B8%8E%E5%B9%B6%E9%9B%86"><span class="nav-number">4.3.</span> <span class="nav-text">映射类型 key值的交集与并集</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Wyatex"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">Wyatex</p>
  <div class="site-description" itemprop="description">这里是我用来做笔记的网站哟~</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">155</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">26</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">97</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/wyatex" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;wyatex" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:wyatex@qq.com" title="E-Mail → mailto:wyatex@qq.com" rel="noopener me" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
    <div class="sidebar-inner sidebar-blogroll">
      <div class="links-of-blogroll animated">
        <div class="links-of-blogroll-title"><i class="fa fa-globe fa-fw"></i>
          链接
        </div>
        <ul class="links-of-blogroll-list">
            <li class="links-of-blogroll-item">
              <a href="https://antfu.me/" title="https:&#x2F;&#x2F;antfu.me&#x2F;" rel="noopener" target="_blank">Anthony Fu</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://www.codesky.me/" title="https:&#x2F;&#x2F;www.codesky.me&#x2F;" rel="noopener" target="_blank">CodeSky</a>
            </li>
            <li class="links-of-blogroll-item">
              <a href="https://learn.lianglianglee.com/" title="https:&#x2F;&#x2F;learn.lianglianglee.com&#x2F;" rel="noopener" target="_blank">技术文章摘抄</a>
            </li>
        </ul>
      </div>
    </div>
        <div class="pjax">
        <div class="sidebar-inner sidebar-post-related">
          <div class="animated">
              <div class="links-of-blogroll-title"><i class="fa fa-signs-post fa-fw"></i>
    相关文章
  </div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/TypeScript/ts%E9%BB%91%E9%AD%94%E6%B3%95%E6%95%99%E5%AD%A6%EF%BC%882%EF%BC%89%EF%BC%9A%E5%BC%80%E5%A7%8B%E7%BB%83%E4%B9%A0%E4%BD%93%E6%93%8D/" rel="bookmark">
        <time class="popular-posts-time">2023-06-28</time>
        <br>
      TypeScript黑魔法教学（2）：开始练习体操
      </a>
    </li>
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/TypeScript/ts%E7%AC%94%E8%AE%B0%EF%BC%885%EF%BC%89%EF%BC%9A%E5%AE%98%E6%96%B9%E5%B7%A5%E5%85%B7%E7%B1%BB%E3%80%81%E6%89%93%E9%80%A0%E8%87%AA%E5%B7%B1%E7%9A%84%E5%B7%A5%E5%85%B7%E7%B1%BB%E5%9E%8B/" rel="bookmark">
        <time class="popular-posts-time">2021-11-13</time>
        <br>
      ts笔记（5）：官方工具类、打造自己的工具类型
      </a>
    </li>
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/TypeScript/ts%E7%AC%94%E8%AE%B0%EF%BC%881%EF%BC%89%EF%BC%9A%E6%90%AD%E5%BB%BA%E5%92%8C%E4%B8%80%E4%BA%9B%E5%9F%BA%E7%A1%80%E7%B1%BB%E5%9E%8B/" rel="bookmark">
        <time class="popular-posts-time">2021-10-28</time>
        <br>
      ts笔记（1）：搭建和一些基础类型
      </a>
    </li>
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/TypeScript/ts%E7%AC%94%E8%AE%B0%EF%BC%884%EF%BC%89%EF%BC%9A%E7%B1%BB%E5%9E%8B%E5%AE%88%E5%8D%AB%E3%80%81%E7%B1%BB%E5%9E%8B%E5%85%BC%E5%AE%B9%E3%80%81%E5%A2%9E%E5%BC%BA%E7%B1%BB%E5%9E%8B%E7%B3%BB%E7%BB%9F/" rel="bookmark">
        <time class="popular-posts-time">2021-11-06</time>
        <br>
      ts笔记（4）：类型守卫、类型兼容、增强类型系统
      </a>
    </li>
    <li class="popular-posts-item">
      <a class="popular-posts-link" href="/TypeScript/ts%E7%AC%94%E8%AE%B0%EF%BC%883%EF%BC%89%EF%BC%9A%E8%81%94%E5%90%88%E7%B1%BB%E5%9E%8B%E3%80%81%E4%BA%A4%E5%8F%89%E7%B1%BB%E5%9E%8B%E3%80%81%E6%9E%9A%E4%B8%BE%E7%B1%BB%E5%9E%8B%E3%80%81%E6%B3%9B%E5%9E%8B/" rel="bookmark">
        <time class="popular-posts-time">2021-11-02</time>
        <br>
      ts笔记（3）：联合类型、交叉类型、枚举类型、泛型
      </a>
    </li>
  </ul>

          </div>
        </div>
        </div>
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wyatex.online/TypeScript/ts%E9%BB%91%E9%AD%94%E6%B3%95%E6%95%99%E5%AD%A6%EF%BC%881%EF%BC%89%EF%BC%9A%E5%89%8D%E7%BD%AE%E7%9F%A5%E8%AF%86/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="Wyatex">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Wyatex`s blog">
      <meta itemprop="description" content="这里是我用来做笔记的网站哟~">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="TypeScript黑魔法教学（1）：前置知识 | Wyatex`s blog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          TypeScript黑魔法教学（1）：前置知识
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-04-20 09:22:12" itemprop="dateCreated datePublished" datetime="2023-04-20T09:22:12+08:00">2023-04-20</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2024-01-12 14:31:44" itemprop="dateModified" datetime="2024-01-12T14:31:44+08:00">2024-01-12</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/TypeScript/" itemprop="url" rel="index"><span itemprop="name">TypeScript</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv">
      <span class="post-meta-item-icon">
        <i class="far fa-eye"></i>
      </span>
      <span class="post-meta-item-text">阅读次数：</span>
      <span id="busuanzi_value_page_pv"></span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>在学习 TS 黑魔法（类型体操），建议先把<a href="/categories/TypeScript/">前面的 TS 基础知识</a>学好了，再来看进阶用法。</p>
<p>另外，即使已经进阶到高级选手了：<strong>不要滥用工具类型，对外暴露的 API，应该尽量多手动标注函数返回值类型。契约高于实现。</strong></p>
<span id="more"></span>

<h2 id="基础"><a href="#基础" class="headerlink" title="基础"></a>基础</h2><h3 id="类型关系"><a href="#类型关系" class="headerlink" title="类型关系"></a>类型关系</h3><img data-src="/TypeScript/ts%E9%BB%91%E9%AD%94%E6%B3%95%E6%95%99%E5%AD%A6%EF%BC%881%EF%BC%89%EF%BC%9A%E5%89%8D%E7%BD%AE%E7%9F%A5%E8%AF%86/type-rel.png" class="">

<p>一图展示顶部类型、底部类型。</p>
<p>类型之间的并集（|）会向上取顶部的类型。即 <code>never | &#39;a&#39; =&gt; &#39;a&#39;</code>，<code>unkown | &#39;a&#39; =&gt; unknown</code></p>
<p>类型之间的交集（&amp;）会向下取底部的类型。即 never &amp; ‘a’ &#x3D; never，unkown &amp; ‘a’ &#x3D;&gt; ‘a’</p>
<ul>
<li>bottom Type: never</li>
<li>top type: unknown</li>
<li>既是 top 也是 bottom: any</li>
</ul>
<h3 id="never"><a href="#never" class="headerlink" title="never"></a>never</h3><p>是其他任意类型的子类型的类型被称为底部类型(bottom type)。</p>
<p><strong>在 TypeScript 中，never 类型便为空类型和底部类型。never 类型的变量无法被赋值，与其他类型求交集为自身，求并集不参与运算。</strong></p>
<h4 id="应用一-联合类型中的过滤"><a href="#应用一-联合类型中的过滤" class="headerlink" title="应用一: 联合类型中的过滤"></a>应用一: 联合类型中的过滤</h4><p>never 在联合类型中会被过滤掉：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> <span class="title class_">Exclude</span>&lt;T, U&gt; = T <span class="keyword">extends</span> U ? <span class="built_in">never</span> : T</span><br><span class="line"></span><br><span class="line"><span class="comment">// 相当于: type A = &#x27;a&#x27;</span></span><br><span class="line"><span class="keyword">type</span> A = <span class="title class_">Exclude</span>&lt;<span class="string">&#x27;x&#x27;</span> | <span class="string">&#x27;a&#x27;</span>, <span class="string">&#x27;x&#x27;</span> | <span class="string">&#x27;y&#x27;</span> | <span class="string">&#x27;z&#x27;</span>&gt;</span><br><span class="line"></span><br><span class="line">T | <span class="built_in">never</span> <span class="comment">// 结果为T</span></span><br><span class="line">T &amp; <span class="built_in">never</span> <span class="comment">// 结果为never</span></span><br></pre></td></tr></table></figure>

<p>取一个映射类型中所有 value 为指定类型的 key。例如，已知某个 React 组件的 props 类型，我需要“知道”（编程意义上）哪些参数是 function 类型。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> <span class="title class_">SomeProps</span> &#123;</span><br><span class="line">  <span class="attr">a</span>: <span class="built_in">string</span></span><br><span class="line">  <span class="attr">b</span>: <span class="built_in">number</span></span><br><span class="line">  <span class="attr">c</span>: <span class="function">(<span class="params">e: MouseEvent</span>) =&gt;</span> <span class="built_in">void</span></span><br><span class="line">  <span class="attr">d</span>: <span class="function">(<span class="params">e: TouchEvent</span>) =&gt;</span> <span class="built_in">void</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 如何得到 &#x27;c&#x27; | &#x27;d&#x27; ？</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">GetKeyByValueType</span>&lt;T, <span class="title class_">Condition</span>&gt; = &#123;</span><br><span class="line">  [K <span class="keyword">in</span> keyof T]: T[K] <span class="keyword">extends</span> <span class="title class_">Condition</span> ? K : <span class="built_in">never</span></span><br><span class="line">&#125;[keyof T]</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">FunctionPropNames</span> = <span class="title class_">GetKeyByValueType</span>&lt;<span class="title class_">SomeProps</span>, <span class="title class_">Function</span>&gt; <span class="comment">// &#x27;c&#x27; | &#x27;d&#x27;</span></span><br></pre></td></tr></table></figure>

<p>运算过程如下：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 第一步，条件映射: type GetKeyByValueType&lt;T, Condition&gt; = &#123;[K in keyof T]: T[K] extends Condition ? K : never&#125;</span></span><br><span class="line">&#123;</span><br><span class="line">  <span class="attr">a</span>: <span class="built_in">never</span></span><br><span class="line">  <span class="attr">b</span>: <span class="built_in">never</span></span><br><span class="line">  <span class="attr">c</span>: <span class="string">&#x27;c&#x27;</span></span><br><span class="line">  <span class="attr">d</span>: <span class="string">&#x27;d&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 第二步，索引取值 &#123;[K in keyof T]: T[K] extends Condition ? K : never&#125;[keyof T]</span></span><br><span class="line"><span class="keyword">type</span> result = <span class="built_in">never</span> | <span class="built_in">never</span> | <span class="string">&#x27;c&#x27;</span> | <span class="string">&#x27;d&#x27;</span></span><br><span class="line"><span class="comment">// 根据never的性质得到：</span></span><br><span class="line"><span class="string">&#x27;c&#x27;</span> | <span class="string">&#x27;d&#x27;</span></span><br></pre></td></tr></table></figure>

<h4 id="应用二：防御性编程"><a href="#应用二：防御性编程" class="headerlink" title="应用二：防御性编程"></a>应用二：防御性编程</h4><p>举个具体点的例子，当你有一个 union type:</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> <span class="title class_">Foo</span> &#123;</span><br><span class="line">  <span class="attr">type</span>: <span class="string">&#x27;foo&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">interface</span> <span class="title class_">Bar</span> &#123;</span><br><span class="line">  <span class="attr">type</span>: <span class="string">&#x27;bar&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">type</span> <span class="title class_">All</span> = <span class="title class_">Foo</span> | <span class="title class_">Bar</span></span><br></pre></td></tr></table></figure>

<p>在 switch 当中判断 type，TS 是可以收窄类型的 (discriminated union)：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">handleValue</span>(<span class="params">val: All</span>) &#123;</span><br><span class="line">  <span class="keyword">switch</span> (val.<span class="property">type</span>) &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">&#x27;foo&#x27;</span>:</span><br><span class="line">      <span class="comment">// 这里 val 被收窄为 Foo</span></span><br><span class="line">      <span class="keyword">const</span> foo = val</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">case</span> <span class="string">&#x27;bar&#x27;</span>:</span><br><span class="line">      <span class="comment">// val 在这里是 Bar</span></span><br><span class="line">      <span class="keyword">const</span> bar = val</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">    <span class="attr">default</span>:</span><br><span class="line">      <span class="comment">// val 在这里是 never</span></span><br><span class="line">      <span class="keyword">const</span> <span class="attr">exhaustiveCheck</span>: <span class="built_in">never</span> = val</span><br><span class="line">      <span class="keyword">break</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>注意在 default 里面我们把被收窄为 never 的 val 赋值给一个显式声明为 never 的变量。如果一切逻辑正确，那么这里应该能够编译通过。但是假如后来有一天你的同事改了 All 的类型：<code>type All = Foo | Bar | Baz</code></p>
<p>然而他忘记了在 handleValue 里面加上针对 Baz 的处理逻辑，这个时候在 default branch 里面 val 会被收窄为 Baz，导致无法赋值给 never，产生一个编译错误。所以通过这个办法，你可以确保 handleValue 总是穷尽 (exhaust) 了所有 All 的可能类型。</p>
<h3 id="unknown"><a href="#unknown" class="headerlink" title="unknown"></a>unknown</h3><p>unknown 指的是不可预先定义的类型，在很多场景下，它可以替代 any 的功能同时保留静态检查的能力。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="attr">num</span>: <span class="built_in">number</span> = <span class="number">10</span></span><br><span class="line">;(num <span class="keyword">as</span> <span class="built_in">unknown</span> <span class="keyword">as</span> <span class="built_in">string</span>).<span class="title function_">split</span>(<span class="string">&#x27;&#x27;</span>) <span class="comment">// 注意，这里和any一样完全可以通过静态检查</span></span><br></pre></td></tr></table></figure>

<p>这个时候 unknown 的作用就跟 any 高度类似了，你可以把它转化成任何类型，不同的地方是，在静态编译的时候，unknown 不能调用任何方法，而 any 可以。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="attr">foo</span>: <span class="built_in">unknown</span> = <span class="string">&#x27;string&#x27;</span></span><br><span class="line">foo.<span class="title function_">substr</span>(<span class="number">1</span>) <span class="comment">// Error: 静态检查不通过报错</span></span><br><span class="line"><span class="keyword">const</span> <span class="attr">bar</span>: <span class="built_in">any</span> = <span class="number">10</span></span><br><span class="line">bar.<span class="title function_">substr</span>(<span class="number">1</span>)</span><br></pre></td></tr></table></figure>

<p>unknown 的一个使用场景是，避免使用 any 作为函数的参数类型而导致的静态类型检查 bug：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">test</span>(<span class="params">input: <span class="built_in">unknown</span></span>): <span class="built_in">number</span> &#123;</span><br><span class="line">  <span class="keyword">if</span> (<span class="title class_">Array</span>.<span class="title function_">isArray</span>(input)) &#123;</span><br><span class="line">    <span class="keyword">return</span> input.<span class="property">length</span> <span class="comment">// Pass: 这个代码块中，类型守卫已经将input识别为array类型</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> input.<span class="property">length</span> <span class="comment">// Error: 这里的input还是unknown类型，静态检查报错。如果入参是any，则会放弃检查直接成功，带来报错风险</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="联合类型"><a href="#联合类型" class="headerlink" title="联合类型"></a>联合类型</h3><p>用 infer 合并类型</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> A&lt;T&gt; = T <span class="keyword">extends</span> &#123; <span class="attr">a</span>: infer U; <span class="attr">b</span>: infer U &#125; ? U : <span class="built_in">any</span></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">Foo</span> = A&lt;&#123; <span class="attr">a</span>: <span class="built_in">number</span>; <span class="attr">b</span>: <span class="built_in">string</span> &#125;&gt; <span class="comment">// type Foo = string | number</span></span><br></pre></td></tr></table></figure>

<h3 id="重载签名的类型不会合并"><a href="#重载签名的类型不会合并" class="headerlink" title="重载签名的类型不会合并"></a>重载签名的类型不会合并</h3><figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 重载签名（函数类型定义）</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">toString</span>(<span class="params">x: <span class="built_in">string</span></span>): <span class="built_in">string</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">toString</span>(<span class="params">x: <span class="built_in">number</span></span>): <span class="built_in">string</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 实现签名（函数体具体实现）</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">toString</span>(<span class="params">x: <span class="built_in">string</span> | <span class="built_in">number</span></span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="title class_">String</span>(x)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">stringOrNumber</span>(<span class="params">x</span>): <span class="built_in">string</span> | <span class="built_in">number</span> &#123;</span><br><span class="line">  <span class="keyword">return</span> x ? <span class="string">&#x27;&#x27;</span> : <span class="number">0</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// input 是 string 和 number 的联合类型</span></span><br><span class="line"><span class="comment">// 即 string | number</span></span><br><span class="line"><span class="keyword">const</span> input = <span class="title function_">stringOrNumber</span>(<span class="number">1</span>)</span><br><span class="line"></span><br><span class="line"><span class="title function_">toString</span>(<span class="string">&#x27;hello&#x27;</span>) <span class="comment">// ok</span></span><br><span class="line"><span class="title function_">toString</span>(<span class="number">2</span>) <span class="comment">// ok</span></span><br><span class="line"><span class="title function_">toString</span>(input) <span class="comment">// error</span></span><br></pre></td></tr></table></figure>

<p>链式的函数可以在返回函数中再添加范型</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> <span class="title class_">Join</span>&lt;</span><br><span class="line">  T <span class="keyword">extends</span> <span class="built_in">string</span>[],</span><br><span class="line">  U <span class="keyword">extends</span> <span class="built_in">string</span>,</span><br><span class="line">  <span class="title class_">Acc</span> <span class="keyword">extends</span> <span class="built_in">string</span> = <span class="string">&#x27;&#x27;</span></span><br><span class="line">&gt; = T <span class="keyword">extends</span> [infer <span class="title class_">First</span> <span class="keyword">extends</span> <span class="built_in">string</span>, ...infer <span class="title class_">Rest</span> <span class="keyword">extends</span> <span class="built_in">string</span>[]]</span><br><span class="line">  ? <span class="title class_">Rest</span> <span class="keyword">extends</span> []</span><br><span class="line">    ? <span class="string">`<span class="subst">$&#123;Acc&#125;</span><span class="subst">$&#123;First&#125;</span>`</span></span><br><span class="line">    : <span class="title class_">Join</span>&lt;<span class="title class_">Rest</span>, U, <span class="string">`<span class="subst">$&#123;Acc&#125;</span><span class="subst">$&#123;First&#125;</span><span class="subst">$&#123;U&#125;</span>`</span>&gt;</span><br><span class="line">  : <span class="title class_">Acc</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">declare</span> <span class="keyword">function</span> join&lt;T <span class="keyword">extends</span> <span class="built_in">string</span>&gt;(</span><br><span class="line">  <span class="attr">delimiter</span>: T</span><br><span class="line">): &lt;S <span class="keyword">extends</span> <span class="built_in">string</span>[]&gt;<span class="function">(<span class="params">...parts: S</span>) =&gt;</span> <span class="title class_">Join</span>&lt;S, T&gt;</span><br><span class="line"></span><br><span class="line"><span class="keyword">declare</span> <span class="keyword">const</span> hyphenJoiner = <span class="title function_">join</span>(<span class="string">&#x27;-&#x27;</span>)</span><br><span class="line"><span class="keyword">declare</span> <span class="keyword">const</span> result = <span class="title function_">hyphenJoiner</span>(<span class="string">&#x27;a&#x27;</span>, <span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;c&#x27;</span>) <span class="comment">// = &#x27;a-b-c&#x27;</span></span><br><span class="line"><span class="title function_">join</span>(<span class="string">&#x27;#&#x27;</span>)(<span class="string">&#x27;a&#x27;</span>, <span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;c&#x27;</span>) <span class="comment">// = &#x27;a#b#c&#x27;</span></span><br></pre></td></tr></table></figure>

<h3 id="泛型"><a href="#泛型" class="headerlink" title="泛型"></a>泛型</h3><p>除了传入的范型，还可以利用传入的范型组合新的范型，就类似像是对一个处理函数，利用函数参数的运算，组合了一个新的在函数作用域内的变量。</p>
<p>举例：Overwrite&lt;T, U&gt;从 U 中的同名属性的类型覆盖 T 中的同名属性类型。(后者中的同名属性覆盖前者)</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Overwrite实现</span></span><br><span class="line"><span class="comment"> * 获取前者独有的key和类型，再取两者共有的key和该key在后者中的类型，最后合并。</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="comment">// 从T中提取存在于U中的key和对应的类型(取交集)</span></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">Intersection</span>&lt;T <span class="keyword">extends</span> <span class="built_in">object</span>, U <span class="keyword">extends</span> <span class="built_in">object</span>&gt; = <span class="title class_">Pick</span>&lt;</span><br><span class="line">  T,</span><br><span class="line">  <span class="title class_">Extract</span>&lt;keyof T, keyof U&gt; &amp; <span class="title class_">Extract</span>&lt;keyof U, keyof T&gt;</span><br><span class="line">&gt;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 从T中排除存在于U中的key和类型</span></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">Diff</span>&lt;T <span class="keyword">extends</span> <span class="built_in">object</span>, U <span class="keyword">extends</span> <span class="built_in">object</span>&gt; = <span class="title class_">Pick</span>&lt;</span><br><span class="line">  T,</span><br><span class="line">  <span class="title class_">Exclude</span>&lt;keyof T, keyof U&gt;</span><br><span class="line">&gt;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">Overwrite</span>&lt;</span><br><span class="line">  T <span class="keyword">extends</span> <span class="built_in">object</span>,</span><br><span class="line">  U <span class="keyword">extends</span> <span class="built_in">object</span>,</span><br><span class="line">  I = <span class="title class_">Diff</span>&lt;T, U&gt; &amp; <span class="title class_">Intersection</span>&lt;U, T&gt;</span><br><span class="line">&gt; = <span class="title class_">Pick</span>&lt;I, keyof I&gt;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@example</span></span></span><br><span class="line"><span class="comment"> * type Eg = &#123; key1: string; other: boolean &#125;</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">Eg</span> = <span class="title class_">Overwrite</span>&lt;&#123; <span class="attr">key1</span>: <span class="built_in">number</span>; <span class="attr">other</span>: <span class="built_in">boolean</span> &#125;, &#123; <span class="attr">key1</span>: <span class="built_in">string</span> &#125;&gt;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 过程</span></span><br><span class="line"><span class="keyword">type</span> a = <span class="title class_">Intersection</span>&lt;&#123; <span class="attr">key1</span>: <span class="built_in">string</span> &#125;, &#123; <span class="attr">key1</span>: <span class="built_in">number</span>; <span class="attr">other</span>: <span class="built_in">boolean</span> &#125;&gt; <span class="comment">// &#123;key1: string&#125;</span></span><br><span class="line"><span class="keyword">type</span> b = <span class="title class_">Diff</span>&lt;&#123; <span class="attr">key1</span>: <span class="built_in">number</span>; <span class="attr">other</span>: <span class="built_in">boolean</span> &#125;, &#123; <span class="attr">key1</span>: <span class="built_in">string</span> &#125;&gt; <span class="comment">// &#123;other: boolean&#125;</span></span><br><span class="line"><span class="keyword">type</span> c = keyof (a &amp; b) <span class="comment">// &#x27;key1&#x27; | &#x27;other&#x27;</span></span><br><span class="line"><span class="keyword">type</span> d = <span class="title class_">Pick</span>&lt;a &amp; b, c&gt; <span class="comment">// &#123; key1: string; other: boolean &#125;</span></span><br></pre></td></tr></table></figure>

<p>过程 d 是将 a 和 b 的合并接口类型转成一个普通的对象类型。</p>
<h3 id="extends-条件语句"><a href="#extends-条件语句" class="headerlink" title="extends 条件语句"></a>extends 条件语句</h3><p>extends 用法和 infer 用法可以看：<a href="/TypeScript/ts%E7%AC%94%E8%AE%B0%EF%BC%885%EF%BC%89%EF%BC%9A%E5%AE%98%E6%96%B9%E5%B7%A5%E5%85%B7%E7%B1%BB%E3%80%81%E6%89%93%E9%80%A0%E8%87%AA%E5%B7%B1%E7%9A%84%E5%B7%A5%E5%85%B7%E7%B1%BB%E5%9E%8B/">官方工具类、打造自己的工具类型</a></p>
<h3 id="递归"><a href="#递归" class="headerlink" title="递归"></a>递归</h3><p>数组和字符串都有自己的递归方法。详细可查阅文档。</p>
<h4 id="数组"><a href="#数组" class="headerlink" title="数组"></a>数组</h4><figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> <span class="title class_">LoopArr</span>&lt;T <span class="keyword">extends</span> <span class="built_in">any</span>[]&gt; = T <span class="keyword">extends</span> [infer P, ...infer R]</span><br><span class="line">  ? <span class="comment">// can do something with P</span></span><br><span class="line">    [P, ...<span class="title class_">LoopArr</span>&lt;R&gt;]</span><br><span class="line">  : []</span><br></pre></td></tr></table></figure>

<p><em>该 example 没有任何实际意义，仅仅展示一下递归的方式</em></p>
<p>如果没有指定特定的子序列，P 是每次都是数组的第一项，达到逐项遍历，你也可以给指定一个子序列，从某一部分开始遍历，譬如 T extends [ 2, 3 , infer P, …infer R]</p>
<h4 id="字符串"><a href="#字符串" class="headerlink" title="字符串"></a>字符串</h4><figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> <span class="title class_">LoopStr</span>&lt;T <span class="keyword">extends</span> <span class="built_in">string</span>&gt; = T <span class="keyword">extends</span> <span class="string">`<span class="subst">$&#123;infer P&#125;</span><span class="subst">$&#123;infer R&#125;</span>`</span></span><br><span class="line">  ? <span class="comment">// can do something with P</span></span><br><span class="line">    <span class="string">`<span class="subst">$&#123;P&#125;</span><span class="subst">$&#123;LoopStr&lt;R&gt;&#125;</span>`</span></span><br><span class="line">  : <span class="string">&#x27;&#x27;</span></span><br></pre></td></tr></table></figure>

<p><em>该 example 没有任何实际意义，仅仅展示一下递归的方式</em></p>
<p>如果没有指定特定的子字符序列，P 是每次都是字符串中的第一个字符，达到逐项遍历，你也可以给指定一个子序列，从某一部分开始遍历，譬如 T extends <code>ABC$&#123;infer P&#125;$&#123;infer R&#125;</code></p>
<h3 id="好用的小特性"><a href="#好用的小特性" class="headerlink" title="好用的小特性"></a>好用的小特性</h3><h4 id="name"><a href="#name" class="headerlink" title="name"></a>name</h4><p>如果你打算通过构造函数以外的其他方式去初始化类中的字段 (例如，也许外部库一定会帮你填充类的一部分)，则可以使用 确定赋值断言运算符 !，它只能被用在你确定安全的地方</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">OKGreeter</span> &#123;</span><br><span class="line">  <span class="comment">// Not initialized, but no error</span></span><br><span class="line">  name!: <span class="built_in">string</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="Type-only-Field-Declarations"><a href="#Type-only-Field-Declarations" class="headerlink" title="Type-only Field Declarations"></a>Type-only Field Declarations</h4><p>当配置文件里的 <code>useDefineForClassFields</code> 是 true 时, 类字段在父类构造函数完成后初始化，覆盖父类设置的任何值。当您只想为继承的字段重新声明更准确的类型时，这可能是一个问题。要处理这些情况，你可以写 声明 向 TypeScript 指示此字段声明不应有运行时效果。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> <span class="title class_">Animal</span> &#123;</span><br><span class="line">  <span class="attr">dateOfBirth</span>: <span class="built_in">any</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">interface</span> <span class="title class_">Dog</span> <span class="keyword">extends</span> <span class="title class_">Animal</span> &#123;</span><br><span class="line">  <span class="attr">breed</span>: <span class="built_in">any</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">AnimalHouse</span> &#123;</span><br><span class="line">  <span class="attr">resident</span>: <span class="title class_">Animal</span></span><br><span class="line">  <span class="title function_">constructor</span>(<span class="params">animal: Animal</span>) &#123;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">resident</span> = animal</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">DogHouse</span> <span class="keyword">extends</span> <span class="title class_ inherited__">AnimalHouse</span> &#123;</span><br><span class="line">  <span class="comment">// Does not emit JavaScript code,</span></span><br><span class="line">  <span class="comment">// only ensures the types are correct</span></span><br><span class="line">  <span class="keyword">declare</span> <span class="attr">resident</span>: <span class="title class_">Dog</span></span><br><span class="line">  <span class="title function_">constructor</span>(<span class="params">dog: Dog</span>) &#123;</span><br><span class="line">    <span class="variable language_">super</span>(dog)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="类型谓词-is"><a href="#类型谓词-is" class="headerlink" title="类型谓词 is"></a>类型谓词 is</h4><p>可以看<a href="/TypeScript/ts%E7%AC%94%E8%AE%B0%EF%BC%884%EF%BC%89%EF%BC%9A%E7%B1%BB%E5%9E%8B%E5%AE%88%E5%8D%AB%E3%80%81%E7%B1%BB%E5%9E%8B%E5%85%BC%E5%AE%B9%E3%80%81%E5%A2%9E%E5%BC%BA%E7%B1%BB%E5%9E%8B%E7%B3%BB%E7%BB%9F/#%E8%87%AA%E5%AE%9A%E4%B9%89%E7%B1%BB%E5%9E%8B%E5%AE%88%E5%8D%AB">类型守卫、类型兼容、增强类型系统</a></p>
<p>通常我们使用 is 关键字（类型谓词）在函数的返回值中，从而对于函数传入的参数进行类型保护。</p>
<h2 id="interface-和-type-关键字"><a href="#interface-和-type-关键字" class="headerlink" title="interface 和 type 关键字"></a>interface 和 type 关键字</h2><p>interface 和 type 两个关键字因为其功能比较接近，常常引起新手的疑问：应该在什么时候用 type，什么时候用 interface？interface 的特点如下：</p>
<ul>
<li>同名 interface 自动聚合，也可以和已有的同名 class 聚合，适合做 polyfill</li>
<li>自身只能表示 object&#x2F;class&#x2F;function 的类型</li>
</ul>
<p>建议库的开发者所提供的公共 api 应该尽量用 interface&#x2F;class，方便使用者自行扩展。举个例子，monaco 缺失了一些需要的 API，所以需要手动 polyfill 一下。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Cloud Studio使用的monaco版本较老0.14.3，和官方文档相比缺失部分功能</span></span><br><span class="line"><span class="comment"> * 另外vscode有一些特有的功能，必须适配</span></span><br><span class="line"><span class="comment"> * 故在这里手动实现作为补充</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">declare</span> <span class="variable language_">module</span> monaco &#123;</span><br><span class="line">  <span class="keyword">interface</span> <span class="title class_">Position</span> &#123;</span><br><span class="line">    <span class="title function_">delta</span>(deltaLineNumber?: <span class="built_in">number</span>, deltaColumn?: <span class="built_in">number</span>): <span class="title class_">Position</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// monaco 0.15.5</span></span><br><span class="line">monaco.<span class="property">Position</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">delta</span> = <span class="keyword">function</span> (<span class="params"></span></span><br><span class="line"><span class="params">  <span class="variable language_">this</span>: monaco.Position,</span></span><br><span class="line"><span class="params">  deltaLineNumber = <span class="number">0</span>,</span></span><br><span class="line"><span class="params">  deltaColumn = <span class="number">0</span></span></span><br><span class="line"><span class="params"></span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> monaco.<span class="title class_">Position</span>(</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">lineNumber</span> + deltaLineNumber,</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">column</span> + deltaColumn</span><br><span class="line">  )</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>与 interface 相比，type 的特点如下：</p>
<ul>
<li>表达功能更强大，不局限于 object&#x2F;class&#x2F;function</li>
<li>要扩展已有 type 需要创建新 type，不可以重名</li>
<li>支持更复杂的类型操作</li>
</ul>
<p>基本上所有用 interface 表达的类型都有其等价的 type 表达。但在实践的过程中，也发现了一种类型只能用 interface 表达，无法用 type 表达，那就是往函数上挂载属性。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> <span class="title class_">FuncWithAttachment</span> &#123;</span><br><span class="line">    (<span class="attr">param</span>: <span class="built_in">string</span>): <span class="built_in">boolean</span>;</span><br><span class="line">    <span class="attr">someProperty</span>: <span class="built_in">number</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="attr">testFunc</span>: <span class="title class_">FuncWithAttachment</span> = ...;</span><br><span class="line"><span class="keyword">const</span> result = <span class="title function_">testFunc</span>(<span class="string">&#x27;mike&#x27;</span>);    <span class="comment">// 有类型提醒</span></span><br><span class="line">testFunc.<span class="property">someProperty</span> = <span class="number">3</span>;    <span class="comment">// 有类型提醒</span></span><br></pre></td></tr></table></figure>

<p>区别表：</p>
<img data-src="/TypeScript/ts%E9%BB%91%E9%AD%94%E6%B3%95%E6%95%99%E5%AD%A6%EF%BC%881%EF%BC%89%EF%BC%9A%E5%89%8D%E7%BD%AE%E7%9F%A5%E8%AF%86/interface-type.png" class="">

<h2 id="反直觉的一些特性"><a href="#反直觉的一些特性" class="headerlink" title="反直觉的一些特性"></a>反直觉的一些特性</h2><h3 id="数组是对象的一种"><a href="#数组是对象的一种" class="headerlink" title="数组是对象的一种"></a>数组是对象的一种</h3><figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Ts 示例：希望 [1, () =&gt; number, string] 能够被处理成 [1, number, string]</span></span><br><span class="line"><span class="comment">// 对象遍历的方式</span></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">GetType1</span>&lt;T <span class="keyword">extends</span> <span class="built_in">any</span>[]&gt; = &#123;</span><br><span class="line">  [K <span class="keyword">in</span> keyof T]: T[K] <span class="keyword">extends</span> () =&gt; infer R ? R : T[K]</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">GetType1Test</span> = <span class="title class_">GetType1</span>&lt;[<span class="number">1</span>, <span class="function">() =&gt;</span> <span class="built_in">number</span>, <span class="built_in">string</span>]&gt;</span><br></pre></td></tr></table></figure>

<p>数组是 key 为 0，1，2 等数字索引的特殊对象，都可以用映射类型的 in 遍历</p>
<h3 id="keyof-索引是公有属性-key-的联合"><a href="#keyof-索引是公有属性-key-的联合" class="headerlink" title="keyof 索引是公有属性 key 的联合"></a>keyof 索引是公有属性 key 的联合</h3><figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> <span class="title class_">Eg1</span> &#123;</span><br><span class="line">  <span class="attr">name</span>: <span class="built_in">string</span></span><br><span class="line">  <span class="keyword">readonly</span> <span class="attr">age</span>: <span class="built_in">number</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// T1的类型实则是name | age</span></span><br><span class="line"><span class="keyword">type</span> <span class="variable constant_">T1</span> = keyof <span class="title class_">Eg1</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Eg2</span> &#123;</span><br><span class="line">  <span class="keyword">private</span> <span class="attr">name</span>: <span class="built_in">string</span></span><br><span class="line">  <span class="keyword">public</span> <span class="keyword">readonly</span> <span class="attr">age</span>: <span class="built_in">number</span></span><br><span class="line">  <span class="keyword">protected</span> <span class="attr">home</span>: <span class="built_in">string</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// T2实则被约束为 age</span></span><br><span class="line"><span class="comment">// 而name和home不是公有属性，所以不能被keyof获取到</span></span><br><span class="line"><span class="keyword">type</span> <span class="variable constant_">T2</span> = keyof <span class="title class_">Eg2</span></span><br></pre></td></tr></table></figure>

<p>索引访问：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">interface</span> <span class="title class_">Eg1</span> &#123;</span><br><span class="line">  <span class="attr">name</span>: <span class="built_in">string</span></span><br><span class="line">  <span class="keyword">readonly</span> <span class="attr">age</span>: <span class="built_in">number</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// string</span></span><br><span class="line"><span class="keyword">type</span> <span class="variable constant_">V1</span> = <span class="title class_">Eg1</span>[<span class="string">&#x27;name&#x27;</span>]</span><br><span class="line"><span class="comment">// string | number</span></span><br><span class="line"><span class="keyword">type</span> <span class="variable constant_">V2</span> = <span class="title class_">Eg1</span>[<span class="string">&#x27;name&#x27;</span> | <span class="string">&#x27;age&#x27;</span>]</span><br><span class="line"><span class="comment">// any</span></span><br><span class="line"><span class="keyword">type</span> <span class="variable constant_">V2</span> = <span class="title class_">Eg1</span>[<span class="string">&#x27;name&#x27;</span> | <span class="string">&#x27;age2222&#x27;</span>]</span><br><span class="line"><span class="comment">// string | number</span></span><br><span class="line"><span class="keyword">type</span> <span class="variable constant_">V3</span> = <span class="title class_">Eg1</span>[keyof <span class="title class_">Eg1</span>]</span><br></pre></td></tr></table></figure>

<p><strong>如果 [] 中的 key 有不存在 T 中的，则是 any；</strong></p>
<p>交叉类型取的多个类型的并集，但是如果相同 key 但是类型不同，则该 key 为 never。</p>
<h3 id="条件类型的分布式特性"><a href="#条件类型的分布式特性" class="headerlink" title="条件类型的分布式特性"></a>条件类型的分布式特性</h3><figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// type A1 = 1</span></span><br><span class="line"><span class="keyword">type</span> <span class="variable constant_">A1</span> = <span class="string">&#x27;x&#x27;</span> <span class="keyword">extends</span> <span class="string">&#x27;x&#x27;</span> ? <span class="number">1</span> : <span class="number">2</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// type A2 = 2</span></span><br><span class="line"><span class="keyword">type</span> <span class="variable constant_">A2</span> = <span class="string">&#x27;x&#x27;</span> | <span class="string">&#x27;y&#x27;</span> <span class="keyword">extends</span> <span class="string">&#x27;x&#x27;</span> ? <span class="number">1</span> : <span class="number">2</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// type A3 = 1 | 2</span></span><br><span class="line"><span class="keyword">type</span> P&lt;T&gt; = T <span class="keyword">extends</span> <span class="string">&#x27;x&#x27;</span> ? <span class="number">1</span> : <span class="number">2</span></span><br><span class="line"><span class="keyword">type</span> <span class="variable constant_">A3</span> = P&lt;<span class="string">&#x27;x&#x27;</span> | <span class="string">&#x27;y&#x27;</span>&gt;</span><br></pre></td></tr></table></figure>

<p>为什么 A2 和 A3 的值不一样？</p>
<ul>
<li>如果用于简单的条件判断，则是直接判断前面的类型是否可分配给后面的类型</li>
<li>若 extends 前面的类型是泛型，且泛型传入的是联合类型时，则会依次判断该联合类型的所有子类型是否可分配给 extends 后面的类型（是一个分发的过程）。</li>
</ul>
<p>总结，就是 extends 前面的参数为联合类型时则会分解（依次遍历所有的子类型进行条件判断）联合类型进行判断。然后将最终的结果组成新的联合类型。</p>
<p>如果不想被分解（分发），做法也很简单，可以通过简单的元组类型包裹以下：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> P&lt;T&gt; = [T] <span class="keyword">extends</span> [<span class="string">&#x27;x&#x27;</span>] ? <span class="number">1</span> : <span class="number">2</span></span><br><span class="line"><span class="comment">// type A4 = 2;</span></span><br><span class="line"><span class="keyword">type</span> <span class="variable constant_">A4</span> = P&lt;<span class="string">&#x27;x&#x27;</span> | <span class="string">&#x27;y&#x27;</span>&gt;</span><br></pre></td></tr></table></figure>

<h3 id="对象字面量的-excess-property-check"><a href="#对象字面量的-excess-property-check" class="headerlink" title="对象字面量的 excess property check"></a>对象字面量的 excess property check</h3><p>子类型中必须包含源类型所有的属性和方法:</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">getPointX</span>(<span class="params">point: &#123; x: <span class="built_in">number</span> &#125;</span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> point.<span class="property">x</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> point = &#123;</span><br><span class="line">  <span class="attr">x</span>: <span class="number">1</span>,</span><br><span class="line">  <span class="attr">y</span>: <span class="string">&#x27;2&#x27;</span>,</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="title function_">getPointX</span>(point) <span class="comment">// OK</span></span><br></pre></td></tr></table></figure>

<p>注意: <strong>如果直接传入一个对象字面量是会报错的</strong>：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">getPointX</span>(<span class="params">point: &#123; x: <span class="built_in">number</span> &#125;</span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> point.<span class="property">x</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="title function_">getPointX</span>(&#123; <span class="attr">x</span>: <span class="number">1</span>, <span class="attr">y</span>: <span class="string">&#x27;2&#x27;</span> &#125;) <span class="comment">// error</span></span><br></pre></td></tr></table></figure>

<p>这是 ts 中的另一个特性，叫做: <strong>excess property check ，当传入的参数是一个对象字面量时，会进行额外属性检查</strong>。</p>
<h3 id="判断never"><a href="#判断never" class="headerlink" title="判断never"></a>判断never</h3><p>先来看一个反直觉的现象：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 1.</span></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">JudgeNever</span> = <span class="built_in">never</span> <span class="keyword">extends</span> <span class="built_in">never</span> ? <span class="literal">true</span> : <span class="literal">false</span>; <span class="comment">// true</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 2.</span></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">TryIsNever</span>&lt;T <span class="keyword">extends</span> <span class="built_in">any</span>&gt; = T <span class="keyword">extends</span> <span class="built_in">never</span> ? <span class="literal">true</span> : <span class="literal">false</span>;</span><br><span class="line"><span class="keyword">type</span> testTryIsNever = <span class="title class_">TryIsNever</span>&lt;<span class="built_in">never</span>&gt; <span class="comment">// never</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 3.</span></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">IsNever</span>&lt;T <span class="keyword">extends</span> <span class="built_in">any</span>&gt; = [T] <span class="keyword">extends</span> [<span class="built_in">never</span>] ? <span class="literal">true</span> : <span class="literal">false</span>;</span><br><span class="line"><span class="keyword">type</span> testIsNever = <span class="title class_">IsNever</span>&lt;<span class="built_in">never</span>&gt;  <span class="comment">// true</span></span><br></pre></td></tr></table></figure>

<p>never是一个特殊的联合类型（它本身是一个底部类型），它没有任何一个成员，而根据Distributive Conditional Types，联合类型作为泛型传入后，会分开计算，因此当输入是never时，因为他一个成员都没有，自然也不需要计算了，直接返回never。而<code>[T]</code>是ts实现的一个特性，能够打破这种Distributive Conditional Types规则。 然后似乎范型默认是当联合类型处理条件语句？所以1和2的结构不同 如果不能理解咱就记住：<code>[T] extends [never]</code>只能这么判断类型是否是never</p>
<h2 id="别的一些知识点"><a href="#别的一些知识点" class="headerlink" title="别的一些知识点"></a>别的一些知识点</h2><h3 id="全局模块-vs-文件模块"><a href="#全局模块-vs-文件模块" class="headerlink" title="全局模块 vs. 文件模块"></a>全局模块 vs. 文件模块</h3><p>当我们没写import或者export的时候，ts会认为我们在写全局模块：</p>
<figure class="highlight ts"><figcaption><span>a.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> foo = <span class="number">1</span></span><br></pre></td></tr></table></figure>

<figure class="highlight ts"><figcaption><span>b.ts</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> bar = foo</span><br></pre></td></tr></table></figure>

<p>要打破这种规则最简单就是加入import或者export</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> bar = foo <span class="comment">// error</span></span><br></pre></td></tr></table></figure>

<h3 id="字符串转数字"><a href="#字符串转数字" class="headerlink" title="字符串转数字"></a>字符串转数字</h3><p>使用场景：字符串的逐个解析有递归特性，我们可以转成字符串后做一些这方面的处理，处理完后还需要转回去</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> <span class="title class_">ToNumber</span>&lt;T&gt; = T <span class="keyword">extends</span> <span class="string">`<span class="subst">$&#123;infer N <span class="keyword">extends</span> <span class="built_in">number</span>&#125;</span>`</span></span><br><span class="line">  ? N</span><br><span class="line">  : T</span><br></pre></td></tr></table></figure>

<h3 id="映射类型-key值的交集与并集"><a href="#映射类型-key值的交集与并集" class="headerlink" title="映射类型 key值的交集与并集"></a>映射类型 key值的交集与并集</h3><figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">type</span> foo = &#123;</span><br><span class="line">  <span class="attr">name</span>: <span class="built_in">string</span>;</span><br><span class="line">  <span class="attr">age</span>: <span class="built_in">string</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> coo = &#123;</span><br><span class="line">  <span class="attr">age</span>: <span class="built_in">number</span>;</span><br><span class="line">  <span class="attr">sex</span>: <span class="built_in">string</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">TestUnion</span> = keyof foo | keyof coo; <span class="comment">// &#x27;name&#x27; | &#x27;age&#x27; | &#x27;sex&#x27;</span></span><br><span class="line"><span class="keyword">type</span> <span class="title class_">TestBoth</span> = keyof (foo | coo);  <span class="comment">// &#x27;age&#x27;</span></span><br></pre></td></tr></table></figure>

<hr>
<p>基本特性已经讲的差不多了，下一篇开始黑魔法的练习</p>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>Wyatex
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://wyatex.online/TypeScript/ts%E9%BB%91%E9%AD%94%E6%B3%95%E6%95%99%E5%AD%A6%EF%BC%881%EF%BC%89%EF%BC%9A%E5%89%8D%E7%BD%AE%E7%9F%A5%E8%AF%86/" title="TypeScript黑魔法教学（1）：前置知识">https://wyatex.online/TypeScript/ts黑魔法教学（1）：前置知识/</a>
  </li>
  <li class="post-copyright-license">
      <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

          <div class="post-tags">
              <a href="/tags/%E5%89%8D%E7%AB%AF/" rel="tag"># 前端</a>
              <a href="/tags/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" rel="tag"># 学习笔记</a>
              <a href="/tags/TypeScript/" rel="tag"># TypeScript</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/%E5%89%8D%E7%AB%AF/js%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB%EF%BC%883%EF%BC%89%EF%BC%9Amitt/" rel="prev" title="js源码阅读（3）：mitt">
                  <i class="fa fa-angle-left"></i> js源码阅读（3）：mitt
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/%E7%BF%BB%E8%AF%91/%E5%A6%82%E4%BD%95%E7%94%A8Rust%E5%92%8CNapi-rs%E5%9C%A8NodeJS%E4%B8%AD%E5%A4%84%E7%90%86CSV%E6%96%87%E4%BB%B6%E5%BF%AB%E4%BA%94%E5%80%8D/" rel="next" title="如何用Rust和Napi-rs在NodeJS中处理CSV文件快五倍">
                  如何用Rust和Napi-rs在NodeJS中处理CSV文件快五倍 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2019 – 
    <span itemprop="copyrightYear">2024</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">Wyatex</span>
  </div>
<div class="busuanzi-count">
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>

    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script size="300" alpha="0.6" zIndex="-1" src="/lib/ribbon.js/dist/ribbon.min.js"></script>
  <script src="/lib/animejs/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="/lib/@next-theme/pjax/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="/lib/@fancyapps/ui/dist/fancybox/fancybox.umd.js" integrity="sha256-q8XkJ6dj5VwSvzI8+nATCHHQG+Xv/dAZBCgqmu93zOY=" crossorigin="anonymous"></script>
  <script src="/lib/lozad/dist/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="/lib/hexo-generator-searchdb/dist/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>



  
  <script data-pjax async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>





</body>
</html>
